import { type MetaFunction, LinksFunction, LoaderFunction, json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
import stylesUrl from "../../styles/imba.css";
import React from "react";

export const links: LinksFunction = () => {
  return [{ rel: "stylesheet", href: stylesUrl }];
};

export const meta: MetaFunction = () => {
  return [
    { title: "IMBA!!" },
    { name: "description", content: "Welcome to IMBA!!" },
    { name: "viewport", content: "width=device-width, initial-scale=1" },
  ];
};

export const loader: LoaderFunction = async () => {
  try {
    const response = await fetch('https://www.customgamestats.com/custom-games/GetGameStats/3349630848', {
      method: 'GET', // 使用 POST 方法
      headers: {
        'accept': '*/*',
        'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'cache-control': 'no-cache',
        'cookie': 'user_device_id=584ac25d17364fcdaa333ef7af2e1da5; user_device_id_timestamp=1729158099621',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://www.customgamestats.com/games/3349630848',
        'sec-ch-ua': '"Google Chrome";v="129", "Not=A?Brand";v="8", "Chromium";v="129"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-origin',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36'
      }
    });

    if (!response.ok) {
      throw new Error("Failed to fetch game stats");
    }

    const data = await response.json();
    return json(data);
  } catch (error) {
    console.error("Error fetching data:", error);
    return json({ error: "Failed to fetch game stats" }, { status: 500 });
  }
};

export default function Index() {
  const initialData = useLoaderData();
  const [data, setData] = React.useState<any>(initialData);

  const fetchData = async () => {
    try {
      const response = await fetch('/imba', {
        method: 'GET',

      }); // 使用当前页面路径请求 loader
      if (!response.ok) {
        throw new Error("Failed to fetch game stats");
      }
      const result = await response.json();
      console.log("resultresultresultresultresult", result)
      setData(result);
    } catch (error) {
      console.error("Error fetching data:", error);
    }
  };

  React.useEffect(() => {
    const intervalId = setInterval(fetchData, 120000); // 每20分钟调用一次

    return () => clearInterval(intervalId); // 清除定时器
  }, []);

  return (
    <div className="imba_page" style={{ fontFamily: "system-ui, sans-serif", lineHeight: "1.2", fontSize: "80px" }}>
      <h1>订阅数</h1>
      <h2>{data?.subscriptions || ''}</h2>
    </div>
  );
}